package com.filmatchs.filmatchs;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.filmatchs.R;
import com.filmatchs.utils.HttpClientManager;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class MovieDetails extends Activity {
	private static final String LOG_TAG = "MovieDetails";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.movie_detail);

		ImageView thumb = (ImageView) findViewById(R.id.cover);
		TextView title = (TextView) findViewById(R.id.title);
		TextView synopsis = (TextView) findViewById(R.id.synopsis);

		Bundle extras = getIntent().getExtras();

		String id = extras.getString("id");

		Movie movie = new Movie();
		try {

			HttpClientManager rc = new HttpClientManager(getResources().getString(
					R.string.SERVICE_URL)
					+ getResources().getString(R.string.MOVIE) + id,
					HttpClientManager.METHOD_GET, "/format/json");

			String jsonString = rc.getResult();
			Log.d(LOG_TAG, jsonString);
			JSONObject jsonO = new JSONObject(jsonString);

			movie.setIdO(jsonO.getString("id")).setImdb_idO(
					jsonO.getString("imdb_id")).setReleasedO(
					jsonO.getString("released")).setRuntimeO(
					jsonO.getString("runtime")).setSynopsisO(
					jsonO.getString("synopsis")).setThumbO(
					jsonO.getString("image")).setTitleO(
					jsonO.getString("title")).setTrailerO(
					jsonO.getString("trailer"));

			thumb.setImageDrawable(LoadImageFromWebOperation(movie.getThumb()));
			title.setText(movie.getTitle());
			synopsis.setText(movie.getSynopsis());

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private Drawable LoadImageFromWebOperation(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, url);
			return d;
		} catch (Exception e) {
			System.out.println("Exc=" + e);
			return null;
		}
	}
}
